<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Films extends Services{
	private $status = TRUE;
	
	function Films(){
		parent::__construct();
				
	}
	
	/******************* PRUEBAS PARA FACEBOOK ******************************/
	public function test(){
		$url_encode			= Sys::$url_base.'services/films/test.json?entro=1';
		$app_id = Sys::$facebook_app_id;
		$app_secret = Sys::$facebook_app_secret;
		if(!isset($_GET['entro'])) {
			$permissions = 'manage_pages,publish_stream,offline_access';//,offline_access,photo_upload,status_update,share_item,video_upload,create_note,
			
	        $dialog_url ="http://www.facebook.com/dialog/oauth?client_id=".$app_id."&redirect_uri=".urlencode($url_encode)."&scope=".$permissions;
			// echo $dialog_url;exit;
			header("Location: ".$dialog_url);
			exit;
	    }else{
	    	
	    	$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$app_id."&redirect_uri=".
			 				$url_encode."&client_secret=".$app_secret."&code=".self::$params['code'];
			$access_token = file_get_contents($token_url);
			var_dump($access_token);
			$page_url			= "https://graph.facebook.com/".Sys::$facebook_id_pelimaniaco."?fields=access_token&".$access_token;
			$page_access_token	= json_decode(file_get_contents($page_url));
        	
			var_dump($page_access_token);
			
			// $graph_url		= "https://graph.facebook.com/me?" . $access_token;
			// $usr_info		= json_decode(file_get_contents($graph_url));
			
	    }
	}
	
	public function datos(){
			
		//	HACE UNA LLAMADA A LA LIBRERIA MY_FACEBOOK PARA PUBLICAR UNA PELICULA O SERIE EN FB	
		$this->load->library('my_facebook');
		var_dump($this->my_facebook->_makePost('films',5));
		exit;
		
		$url	= 'https://graph.facebook.com/'.Sys::$facebook_id_pelimaniaco.'/feed';
				
				$data = array(
								'access_token'	=> 'AAAEPF4cxo2kBADZBzAif3KwODU9ZBw3ZB6LDZBWZCcps3HjOo5kZAEyFQTZBsl7x2HgYDMBpbQEpLGcZAXELQKRhahNDb7IYlZBOpng9DsaedQQZDZD',
								'message'		=> "Message \n Message",
								'link'			=> 'http://www.pelimaniaco.com' ,
								'picture'		=> 'http://www.pelimaniaco.com/skins/default/images/logo_boleto.png',
								'name'			=> 'Name' ,
								'caption'		=> 'caption',
								'description'	=>  'Description',
								'properties'	=> "[{'text': 'Ver mas...','href': 'http://www.pelimaniaco.com'}]",
								'actions'		=> json_encode (array('name'=>'Ver mas Peliculas', 'link'=>'http://www.pelimaniaco.com'))
						);
		
		$res = $this->my_facebook->curlExec($url,$data);
		
		var_dump($res->id);
	}
	
	/******************* PRUEBAS PARA FACEBOOK ******************************/
	
	protected function add(){
		$this->checkAccessToken();
		$response_validate	= $this->validate('add');
		
		if($this->status){
			$this->load->model('films_model');
			$data	= $this->films_model->saveInfoFilm(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			else
				throw new NotExistException('pelicula');
		}
		else
			throw new UserValidateException(implode(',',$response_validate));
	}
	
	protected function update(){
		$this->checkAccessToken();
		$response_validate	= $this->validate('update');
		
		if($this->status){
			$this->load->model('films_model');
			$data	= $this->films_model->updateInfoFilm(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			else
				throw new NotExistException('pelicula');
		}
		else
			throw new UserValidateException(implode(',',$response_validate));
	}

	protected function get(){
		$this->checkAccessToken();
		$response_validate	= $this->validate('get');
		
		if ($this->status) {
			$this->load->model('films_model');
			$data	= $this->films_model->getInfoFilm(self::$params);
			if (is_array($data)) {
				return $this->parseOutput($data);
			}
			else
				throw new NotExistException('pelicula');
		}
		else
			throw new UserValidateException(implode(',', $response_validate));
		
	}
	
	protected function search_movies_tmdb(){
		$this->checkAccessToken();
		$response_validate	= $this->validate('search_movies_tmdb');
		
		if($this->status){
			$this->load->model('films_model');
			$data	= $this->films_model->getMoviesListTmdb(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
		}
		else
			throw new UserValidateException(implode(',', $response_validate));
	}
	
	protected function get_info_tmdb(){
		$this->checkAccessToken();
		$response_validate	= $this->validate('get_info_tmdb');
		
		if($this->status){
			$this->load->model('films_model');
			$data	= $this->films_model->getInfoMovieTmdb(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
		}
		else
			throw new UserValidateException(implode(',', $response_validate));
	}
		
	private function validate_add(){
		
		$validate = new MY_Form_validation();
		$validate->setArrayValidate(self::$params);

		$poster_validate = array();
		
		if(!isset($_FILES['poster']) && !isset(self::$params['poster'])){
			$poster_validate = array(
					'field'	=> 'poster',
					'label'	=> 'poster',
					'rules'	=> 'required'
			);
		}
		else if(isset($_FILES['poster']) && isset(self::$params['poster'])){
			if(empty($_FILES['poster']['name']) && empty(self::$params['poster']))
				$poster_validate = array(
					'field'	=> 'poster',
					'label'	=> 'poster',
					'rules'	=> 'required'
				);
		}
		else if(isset($_FILES['poster']) && !isset(self::$params['poster'])){
			if(empty($_FILES['poster']['name']))
				$poster_validate = array(
					'field'	=> 'poster',
					'label'	=> 'poster',
					'rules'	=> 'required'
				);	
		} 
		else if(!isset($_FILES['poster']) && isset(self::$params['poster'])){
			if(empty(self::$params['poster']))
				$poster_validate = array(
					'field'	=> 'poster',
					'label'	=> 'poster',
					'rules'	=> 'required'
				);	
		}

		$config	= array(
							array(
									'field'	=> 'title',
									'label'	=> 'title',
									'rules'	=> 'required|max_length[100]'
							),
							$poster_validate
							,
							array(
									'field'	=> 'date_release',
									'label'	=> 'date_release',
									'rules'	=> 'max_length[10]'
							),
							array(
									'field'	=> 'languaje',
									'label'	=> 'languaje',
									'rules'	=> 'max_length[20]'
							),
							array(
									'field'	=> 'subtitle',
									'label'	=> 'subtitle',
									'rules'	=> 'max_length[20]'
							),
							array(
									'field'	=> 'format_film',
									'label'	=> 'format_film',
									'rules'	=> 'max_length[10]'
							),
							array(
									'field'	=> 'quality',
									'label'	=> 'quality',
									'rules'	=> 'max_length[25]'
							),
							array(
									'field'	=> 'duration',
									'label'	=> 'duration',
									'rules'	=> 'max_length[30]'
							),
							array(
									'field'	=> 'size',
									'label'	=> 'size',
									'rules'	=> 'max_length[20]'
							),
							array(
									'field'	=> 'synopsis_spa',
									'label'	=> 'synopsis_spa',
									'rules'	=> ''
							),
							array(
									'field'	=> 'synopsis_eng',
									'label'	=> 'synopsis_eng',
									'rules'	=> ''
							),
							array(
									'field'	=> 'trailers',
									'label'	=> 'trailers',
									'rules'	=> 'max_length[32]'
							),
							array(
									'field'	=> 'coming_soon',
									'label'	=> 'coming_soon',
									'rules'	=> 'expression:/^(0|1)$/'
							),
							array(
									'field'	=> 'categories[]',
									'label'	=> 'categories[]',
									'rules'	=> 'is_natural_no_zero'
							),
							array(
									'field'	=> 'cast[]',
									'label'	=> 'cast[]',
									'rules'	=> 'is_natural_no_zero'
							),
							array(
									'field'	=> 'servers[]',
									'label'	=> 'servers[]',
									'rules'	=> 'is_natural_no_zero'
							),
							array(
									'field'	=> 'sources[]',
									'label'	=> 'sources[]',
									'rules'	=> 'max_length[150]'
							),
							array(
									'field'	=> 'online[]',
									'label'	=> 'online[]',
									'rules'	=> 'expression:/^(0|1)$/'
							),
							array(
									'field'	=> 'on_fb',
									'label'	=> 'on_fb',
									'rules'	=> 'expression:/^(0|1)$/'
							)
					);
		
		$validate->set_rules($config);
		$this->status = $validate->run();
		
		//	VALIDA QUE LA CANTIDAD DE servers[] SEA IGUAL A LA CANTIDAD DE sources[]
		//	VALIDA QUE LAS URLS DENTRO DE $sources[] SEAN VALIDAS

		if(isset(self::$params["servers"]) && isset(self::$params['sources']) && isset(self::$params['online'])){
    		if(count(self::$params["servers"]) != count(self::$params["sources"])){
    			$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_missing_params','servers[]','sources[]','online[]');
    		}
			else if(count(self::$params["servers"]) != count(self::$params["online"])){
				$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_missing_params','servers[]','sources[]','online[]');
			}
			
			if($this->status)
				foreach (self::$params["sources"] as $key => $itm)
					if(!sys::urlValid($itm)){
	    				$this->status = FALSE;
						$validate->_error_array['values'] = lang('txt_invalid_url','sources => "'.$itm.'"');
					}
		}

		//	VALIDA QUE LA URL DEL $PARAMS['POSTER'] SEA VALIDA.
		if(isset(self::$params["poster"])){
			$url = self::$params['poster'];
			if(!sys::urlValid($url)){
    			$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_invalid_url', 'poster => "'.$url.'"');
			}
    	}
		
		//	VALIDA QUE LA URL DEL $PARAMS['SCREENSHOTS'] SEA VALIDA.
		if(isset(self::$params["screenshots"])){
			$url = self::$params['screenshots'];
			if(!sys::urlValid($url)){
    			$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_invalid_url', 'screenshots => "'.$url.'"');
			}
    	}
		
		//	VALIDA QUE LA FECHA DATE_RELEASE SEA VALIDA.
		$fecha = new Fecha();
		if(isset(self::$params['date_release'])){
			if(!$fecha->is_date(self::$params['date_release'])){
				$this->status = FALSE;
				$validate->_error_array['date_release'] = lang('txt_invalid_date').' (date_release)';
			}
		}
		
		return $validate->_error_array;
	}
	
	private function validate_update(){
		
		$validate = new MY_Form_validation();
		$validate->setArrayValidate(self::$params);

		$config	= array(
							array(
									'field'	=> 'id_film',
									'label'	=> 'id_film',
									'rules'	=> 'required|is_natural_no_zero'
							),array(
									'field'	=> 'title',
									'label'	=> 'title',
									'rules'	=> 'required|max_length[100]'
							),
							array(
									'field'	=> 'date_release',
									'label'	=> 'date_release',
									'rules'	=> 'max_length[10]'
							),
							array(
									'field'	=> 'languaje',
									'label'	=> 'languaje',
									'rules'	=> 'max_length[20]'
							),
							array(
									'field'	=> 'subtitle',
									'label'	=> 'subtitle',
									'rules'	=> 'max_length[20]'
							),
							array(
									'field'	=> 'format_film',
									'label'	=> 'format_film',
									'rules'	=> 'max_length[10]'
							),
							array(
									'field'	=> 'quality',
									'label'	=> 'quality',
									'rules'	=> 'max_length[25]'
							),
							array(
									'field'	=> 'duration',
									'label'	=> 'duration',
									'rules'	=> 'max_length[30]'
							),
							array(
									'field'	=> 'size',
									'label'	=> 'size',
									'rules'	=> 'max_length[20]'
							),
							array(
									'field'	=> 'synopsis_spa',
									'label'	=> 'synopsis_spa',
									'rules'	=> ''
							),
							array(
									'field'	=> 'synopsis_eng',
									'label'	=> 'synopsis_eng',
									'rules'	=> ''
							),
							array(
									'field'	=> 'trailers',
									'label'	=> 'trailers',
									'rules'	=> 'max_length[32]'
							),
							array(
									'field'	=> 'coming_soon',
									'label'	=> 'coming_soon',
									'rules'	=> 'expression:/^(0|1)$/'
							),
							array(
									'field'	=> 'categories[]',
									'label'	=> 'categories[]',
									'rules'	=> 'is_natural_no_zero'
							),
							array(
									'field'	=> 'cast[]',
									'label'	=> 'cast[]',
									'rules'	=> 'is_natural_no_zero'
							),
							array(
									'field'	=> 'servers[]',
									'label'	=> 'servers[]',
									'rules'	=> 'is_natural_no_zero'
							),
							array(
									'field'	=> 'sources[]',
									'label'	=> 'sources[]',
									'rules'	=> 'max_length[150]'
							),
							array(
									'field'	=> 'on_fb',
									'label'	=> 'on_fb',
									'rules'	=> 'expression:/^(0|1)$/'
							)
							
					);
		
		$validate->set_rules($config);
		$this->status = $validate->run();
		
		//	VALIDA QUE LA CANTIDAD DE servers[] SEA IGUAL A LA CANTIDAD DE sources[]
		//	VALIDA QUE LAS URLS DENTRO DE $sources[] SEAN VALIDAS
		if(isset(self::$params["servers"]) && isset(self::$params['sources']) && isset(self::$params['online'])){
    		if(count(self::$params["servers"]) != count(self::$params["sources"])){
    			$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_missing_params','servers[]','sources[]','online[]');
    		}
			else if(count(self::$params["servers"]) != count(self::$params["online"])){
				$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_missing_params','servers[]','sources[]','online[]');
			}
			
			if($this->status)
				foreach (self::$params["sources"] as $key => $itm)
					if(!sys::urlValid($itm)){
	    				$this->status = FALSE;
						$validate->_error_array['values'] = lang('txt_invalid_url','sources => "'.$itm.'"');
					}
		}

		//	VALIDA QUE LA URL DEL $PARAMS['POSTER'] SEA VALIDA.
		if(isset(self::$params["poster"])){
			$url = self::$params['poster'];
			if(!sys::urlValid($url)){
    			$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_invalid_url', 'poster => "'.$url.'"');
			}
    	}
		
		//	VALIDA QUE LA URL DEL $PARAMS['SCREENSHOTS'] SEA VALIDA.
		if(isset(self::$params["screenshots"])){
			$url = self::$params['screenshots'];
			if(!sys::urlValid($url)){
    			$this->status = FALSE;
    			$validate->_error_array['values'] = lang('txt_invalid_url', 'screenshots => "'.$url.'"');
			}
    	}
		
		//	VALIDA QUE LA FECHA DATE_RELEASE SEA VALIDA.
		$fecha = new Fecha();
		if(isset(self::$params['date_release'])){
			if(!$fecha->is_date(self::$params['date_release'])){
				$this->status = FALSE;
				$validate->_error_array['date_release'] = lang('txt_invalid_date').' (date_release)';
			}
		}
		
		return $validate->_error_array;
	}	
	
	
	private function validate_get(){
		$validate	= new MY_Form_validation();
		$validate->setArrayValidate(self::$params);
		
		$config = array(
							array(
								'field' => 'id_film',
								'label' => 'id_film',
								'rules' => 'required|is_natural_no_zero'
							)
		);
		$validate->set_rules($config);
		$this->status = $validate->run();
		
		return $validate->_error_array;
		
	}
	
	private function validate_search_movies_tmdb(){
		
		$validate	= new MY_Form_validation();
		$validate->setArrayValidate(self::$params);
		
		$config	= array(
							array(
									'field' => 'name_movie',
									'label'	=> 'name_movie',
									'rules'	=> 'required'
							)	
					);
		
		$validate->set_rules($config);
		$this->status = $validate->run();
		
		//	VALIDA QUE LA FECHA YEAR SEA VALIDA.
		$fecha = new Fecha();
		if(isset(self::$params['year'])){
			if(!$fecha->is_date(self::$params['year'])){
				$this->status = FALSE;
				$validate->_error_array['year'] = lang('txt_invalid_date').' (year)';
			}
		}
		
		return $validate->_error_array;
	}
	
	private function validate_get_info_tmdb(){
		
		$validate	= new MY_Form_validation();
		$validate->setArrayValidate(self::$params);
		
		$config	= array(
							array(
									'field' => 'id_tmdb',
									'label'	=> 'id_tmdb',
									'rules'	=> 'required|is_natural_no_zero'
							),
							array(
									'field' => 'idiom',
									'label'	=> 'idiom',
									'rules'	=> 'max_length[2]'
							)
							
					);
		
		$validate->set_rules($config);
		$this->status = $validate->run();
		
		//	VALIDA EL LENGUAJE EN CASO DE HABERLO ESPECIFICADO
		if(isset(self::$params['idiom'])){
			if(!in_array(self::$params['idiom'], array('en','es','fr'))){
				$this->status = FALSE;
				$validate->_error_array['idiom'] = lang('txt_invalid_lang_info',self::$params['idiom']);
			}
		}
		
		return $validate->_error_array;
	}

	
	/**
     * Permite incorporar las validaciones bases que apliquen para todos los servicios.
     * Validaciones mas espesificas tendran que ser en cada servicio en particular.
     * @author gama
     */
    private function validate($val_method){
    	if(method_exists($this, 'validate_'.$val_method)){
    		$this->load->library('MY_Form_validation');
    		return $this->{'validate_'.$val_method}();
    	}
    }
	
	private function parseOutput($data=array(), $only_parse=false){
		if ($only_parse)
			return $this->{'_format_'.$this->getFormat()}($data);
		if($this->status==true){
			return $this->{'_trim_format_'.$this->getFormat()}(
					$this->{'_format_'.$this->getFormat()}($data)
					);
		}
    }
	
}
